<template>

	<view class="contain">
		<view class="content">
			<!-- 注意，如果需要兼容微信小程序，最好通过setRules方法设置rules规则 -->
			<u--form labelPosition="left" :model="userInfo" :rules="rules" ref="form1" labelWidth="80">
				<!-- 请假人 -->
				<u-form-item label="请假人:" v-model="userInfo.name" borderBottom ref="item1" required><u--input disabled
						disabledColor='#f9f9f9' v-model="userInfo.name" border="none"></u--input></u-form-item>
				<!-- 班级 -->
				<u-form-item label="班级:" v-model="userInfo.class" borderBottom ref="item1" required><u--input disabled
						disabledColor='#f9f9f9' v-model="userInfo.class" border="none"></u--input></u-form-item>
				<!-- 联系方式 -->
				<u-form-item label="联系方式:" v-model="userInfo.phone" borderBottom ref="item1" required><u--input
						v-model="userInfo.phone" border="none"></u--input></u-form-item>
				<!-- 报修类型 -->
				<u-form-item label="请假类型:" prop="type" borderBottom @click="openAction('请假类型')" ref="item1" required>
					<u--input v-model="userInfo.type" disabled disabledColor="#ffffff" placeholder="请选择请假类型"
						border="none"></u--input>
					<u-icon slot="right" name="arrow-right"></u-icon>
				</u-form-item>
				<!-- 主要症状 -->
				<u-form-item v-if='showMalady' label="主要症状:" prop="symptom" borderBottom @click="openAction('主要症状')"
					ref="item1" required>
					<u--input v-model="userInfo.symptom" disabled disabledColor="#ffffff" placeholder="请选择症状"
						border="none"></u--input>
					<u-icon slot="right" name="arrow-right"></u-icon>
				</u-form-item>
				<!-- 请假时间 -->
				<u-form-item label="开始时间:" prop="startTime" borderBottom @click="openDate('start')" ref="item1"
					required>
					<view class=""><u--input v-model="userInfo.startTime" disabled disabledColor="#ffffff"
							placeholder="请选择开始时间" border="none"></u--input></view>
				</u-form-item>
				<u-form-item label="结束时间:" prop="endTime" borderBottom @click="openDate('end')" ref="item1" required>
					<view class=""><u--input v-model="userInfo.endTime" disabled disabledColor="#ffffff"
							placeholder="请选择结束时间" border="none"></u--input></view>
				</u-form-item>

				<!-- 请假时长 -->
				<u-form-item label="请假时长:" prop='durationDay' borderBottom ref="item1" required>
					<u--input v-model="userInfo.durationDay" placeholder="请输入请假时长" disabledColor="#ffffff"
						border="none"></u--input>

				</u-form-item>
				<u-form-item label="请假事由:" prop="content" borderBottom ref="item1" required>
					<u--textarea v-model="userInfo.content" placeholder="请输入请假事由"></u--textarea>
				</u-form-item>
				<!-- 是否新增 -->
				<u-form-item v-if='showMalady' label="是否新增:"  borderBottom ref="item1" >
					<radio-group @change="changeisIncreased">
						<radio color="#1cb8a7;" style="transform: scale(0.6);" value="0"
							:checked="userInfo.isIncreased == '0'" />
						是
						<radio color="#1cb8a7;" style="transform: scale(0.6);margin-left: 10px;" value="1"
							:checked="userInfo.isIncreased == '1'" />
						否
					</radio-group>
				</u-form-item>
				<!-- 是否就诊 -->
				<u-form-item v-if='showMalady' label="是否就诊:"  borderBottom ref="item1" >
					<radio-group @change="changeOutpatients">
						<radio color="#1cb8a7;" style="transform: scale(0.6);" value="0"
							:checked="userInfo.outpatients == '0'" />
						是
						<radio color="#1cb8a7;" style="transform: scale(0.6);margin-left: 10px;" value="1"
							:checked="userInfo.outpatients == '1'" />
						否
					</radio-group>
				</u-form-item>
				<!-- 何处就诊 -->
				<u-form-item v-if='showMalady' label="何处就诊:"  borderBottom ref="item1" >
					<u--input  v-model="userInfo.whereOutpatients" placeholder="请填写就诊地方"  border="none"></u--input>
				</u-form-item>
				<!-- 诊断结果 -->
				<u-form-item v-if='showMalady' label="诊断结果:"  borderBottom ref="item1" >
					<u--input  v-model="userInfo.diagnose" placeholder="请填写诊断结果"  border="none"></u--input>
				</u-form-item>
				<!-- 目前状况 -->
				<u-form-item v-if='showMalady' label="目前状况:"  borderBottom ref="item1" >
					<radio-group @change="changeCurrentStatus">
						<radio color="#1cb8a7;" style="transform: scale(0.6);" value="0"
							:checked="userInfo.currentStatus == '0'" />
						在家
						<radio color="#1cb8a7;" style="transform: scale(0.6);margin-left: 10px;" value="1"
							:checked="userInfo.currentStatus == '1'" />
						住院
					</radio-group>
				</u-form-item>
				<!-- <view class="u-page__tag-item" v-for="(item, index) in radios" :key="index">
					<u-tag  borderColor='#1cb8a7' :bgColor='item.checked?"#1cb8a7":"#fff"'
						:color='!item.checked?"#1cb8a7":"#fff"' :text="item.name" :plain="!item.checked" type="warning"
						:name="index" @click="radioClick(item,index)">
					</u-tag>
				</view> -->
				
				<!-- <u-form-item v-for='(it,i) in userInfo.checkUser' :key="i" label="审批人:" prop="userInfo.type"
					borderBottom @click="openAction('审批人')" ref="item1" required>
					<u--input v-model="it.name" disabled disabledColor="#ffffff" placeholder="请选择审批人"
						border="none"></u--input>
					<u-icon slot="right" name="arrow-right"></u-icon>
				</u-form-item> -->
				<u-form-item label="上传附件:" borderBottom ref="item1">
					<u-upload :previewFullImage="true" :fileList="fileList1" @afterRead="afterRead" @delete="deletePic"
						name="1" multiple :maxCount="10"></u-upload>
				</u-form-item>
			</u--form>
			<button @click="submit" class="btn">提交</button>
			<u-datetime-picker :minDate='minDate' :show="showDate" @cancel="showDate = false" @confirm="selectDate"
				v-model="dateTime" mode="date"></u-datetime-picker>

			<u-action-sheet :round='10' :show="showSex" :actions="actions" :title="actionTitle" @close="showSex = false"
				@select="Select"></u-action-sheet>

		</view>
		<!-- <u-tabbar :value="tabbarIndex" @change="click" :fixed="true" :border="true" activeColor='#1cb8a7'>
			<u-tabbar-item text="申请" icon="edit-pen-fill" @click='clickTabbar'></u-tabbar-item>
			<u-tabbar-item text="列表" icon="file-text-fill" @click='clickTabbar'></u-tabbar-item>

		</u-tabbar> -->
	</view>
</template>

<script>
	import {
		pageStaff
	} from '@/api/workers.js';
	import {
		leaveType,
		saveLeaveApply
	} from '@/api/leave.js';
	export default {
		options: {
			styleIsolation: 'shared'
		}, //解决/deep/不生效**
		data() {
			return {
				showSex: false,
				minDate: Date.parse(new Date()),
				userInfo: {
					name: this.$util.getChild().userName,
					phone: this.$util.getUser().phone,
					class: this.$util.getChild().className,
					type: '',
					duration: '', //时长
					durationDay: '',
					startTime: '',
					endTime: '',
					content: '', //报修内容
					typeId: '',
					// checkUser: [{
					// 	name: ''
					// }, ]
					outpatients: '', //是否就诊
					isIncreased: '', //是否新增
					diagnose: '', //诊断结果 
					symptom: '', //症状
					currentStatus: '', //0/在家，1/住院 ,目前状况
					whereOutpatients: '' //何处就诊
				},
				dateTime: Number(new Date()),
				actions: [],
				rules: {
					'type': {
						type: 'string',
						required: true,
						message: '请选择类型',
						trigger: ['blur', 'change']
					},
					"symptom":{
						type: 'string',
						required: true,
						message: '请选择症状',
						trigger: ['blur', 'change']
					},
					'content': {
						type: 'string',
						required: true,
						message: '请填写请假事由',
						trigger: ['blur', 'change']
					},
					'startTime': {
						type: 'string',
						required: true,
						message: '请选择开始时间',
						trigger: ['blur', 'change']
					},
					'endTime': {
						type: 'string',
						required: true,
						message: '请选择结束时间',
						trigger: ['blur', 'change']
					},
					"durationDay": {
						type: 'string',
						required: true,
						message: '请填写请假时长',
					}
				},
				radio: '',
				switchVal: false,
				actionTitle: '请选择报修类型',
				showDate: false, //日期选择
				fileList1: [], //上传图片
				tabbarIndex: 0,
				dateType: 'start',
				checkPerson: [],
				leaveType: [],
				radios: [],
				activeIndex: '', //病症
				showMalady: false,
				newDate:{}
			};
		},
		watch: {
			radios: {
				handler(newVal, oldVal) {
					newVal.forEach(it => {
						if (it.checked) {
							this.userInfo.content = this.userInfo.content + it.name
						} else {
							this.userInfo.content = this.userInfo.content.replace(it.name, '')
						}
					})
				},
				deep: true,
			},

		},
		onLoad(op) {
			if(op.edit){
			    this.newDate = JSON.parse(op.edit);
				console.log('newDatenewDate',this.newDate);
				this.userInfo.name = this.newDate.attendUserName;
                this.userInfo.class = this.newDate.className;
				this.userInfo.startTime = this.newDate.attendDay;
				this.userInfo.endTime = this.newDate.attendDay;
				this.userInfo.durationDay = '1天'
			}
			// 获取请假类型
			// "typeId": "string",
			// "typeName": "string",
			this.getleaveType()
			// 获取审批人
			// 受理人角色获取
			this.getPageStaff({
				roleId: '1646810116958998530'
			})
			// 获取字典项
			this.getDiction()
			// this.getToken()
		},
		methods: {
			// 是否新增
			changeisIncreased(e) {
				this.userInfo.isIncreased = e.detail.value
				console.log('eeeeeeeeee', e.detail.value);
			},
			// 是否就诊
			changeOutpatients(e){
				this.userInfo.outpatients = e.detail.value
			},
			// 目前状况
			changeCurrentStatus(e){
				this.userInfo.currentStatus = e.detail.value
			},
			// 获取字典项
			getDiction() {
				let radio = this.$util.getdictionary('病症');
				console.log('sssssssssssssss字典项', radio)
				if (radio) {
					radio.forEach((item, i) => {
						this.radios.push({
							name: item.name,
							id: item.id,
						});
					})
				}


			},
			radioClick(it, i) {
				this.activeIndex = i;
				this.radios.map((itm, index) => {
					if (i == index) {
						if (itm.checked) {
							itm.checked = false
						} else {
							itm.checked = true
						}

					} else {
						itm.checked = false
					}
					return itm
				})

				console.log('this.radios', this.radios)
				// this.getData(this.params)
			},
			// 获取审批人
			async getPageStaff(pa) {
				const {
					data
				} = await pageStaff(pa)
				console.log('打印返回', data)
				if (data.code == 0) {
					data.data.list.forEach(it => {
						this.checkPerson.push({
							name: it.userName,
							id: it.userId
						})
					})

				}
			},
			// 获取请假类型
			async getleaveType() {
				const {
					data
				} = await leaveType()

				if (data.code == 0) {
					data.data.list.forEach(it => {
						this.leaveType.push({
							name: it.typeName,
							id: it.typeId
						})
					})

				}

			},
			openDate(type) {
				this.showDate = true;
				this.dateType = type
			},
			clickTabbar(e) {
				this.tabbarIndex = e
				console.log('eeeee', e)
				if (this.tabbarIndex == 0) {
					uni.redirectTo({
						url: '/pages/subPack/leave/apply'
					})
				} else if (this.tabbarIndex == 1) {
					uni.redirectTo({
						url: '/pages/subPack/leave/list'
					})
				}
			},
			click() {

			},
			// 删除图片
			deletePic(event) {
				this[`fileList${event.name}`].splice(event.index, 1);
			},
			// 新增图片
			async afterRead(event) {
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file);
				console.log('选择图片', event.file);
				let fileListLen = this[`fileList${event.name}`].length;
				lists.map(item => {
					this[`fileList${event.name}`].push({
						...item,
						status: 'uploading',
						message: '上传中'
					});
				});
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url);
					let item = this[`fileList${event.name}`][fileListLen];
					this[`fileList${event.name}`].splice(
						fileListLen,
						1,
						Object.assign(item, {
							status: 'success',
							message: '',
							url: result
						})
					);
					fileListLen++;
				}
			},
			uploadFilePromise(url) {
				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
						url: this.$config.URL + 'api/app/sysFile/v1/save', // 仅为示例，非真实的接口地址
						filePath: url,
						name: 'file',
						formData: {
							user: 'test'
						},
						success: res => {
							resolve(JSON.parse(res.data).url);

						}
					});
				});
			},
			selectDate(d) {
				if (this.dateType == 'start') {
					this.userInfo.startTime = this.format(d.value);
				} else {

					this.userInfo.endTime = this.format(d.value);
				}
				if (this.userInfo.startTime && this.userInfo.endTime) {

					this.userInfo.duration = this.getDays(this.userInfo.startTime, this
						.userInfo.endTime)
					if (this.userInfo.duration > 0 || this.userInfo.duration == 0) {
						this.userInfo.durationDay = this.userInfo.duration + '天'
					} else {
						this.$api.showTip('结束时间不能小于开始时间')
					}

				}

				this.showDate = false;

			},
			format(shijianchuo) {
				//shijianchuo是整数，否则要parseInt转换
				var time = new Date(shijianchuo);
				var y = time.getFullYear();
				var m = time.getMonth() + 1;
				var d = time.getDate();
				var h = time.getHours();
				var mm = time.getMinutes();
				var s = time.getSeconds();
				return y + '-' + this.add0(m) + '-' + this.add0(d)
			},
			add0(m) {
				return m < 10 ? '0' + m : m;
			},
			// 提交
			submit() {
				if (new Date(this.userInfo.startTime) > new Date(this.userInfo.endTime)) {
					return this.$api.showTip('开始时间不能大于结束时间')
				}
				let self = this
				
				this.$refs.form1.validate().then(res => {
					var data = { 
						applyMobile: this.userInfo.phone,
						applyUserId: this.newDate.attendUserId?this.newDate.attendUserId:this.$util.getChild().userId,
						applyUserName: this.newDate.attendUserName?this.newDate.attendUserName:this.$util.getChild().userName,
						classId: this.newDate.classId?this.newDate.classId:this.$util.getChild().classId,
						className: this.newDate.className?this.newDate.className:this.$util.getChild().className,
						endTime: this.userInfo.endTime,
						leaveImg: JSON.stringify(this.fileList1.map(it => it.url)),
						leaveReason: this.userInfo.content,
						leaveTime: this.userInfo.duration,
						startTime: this.userInfo.startTime,
						leaveType: this.userInfo.typeId,
						leaveName: this.userInfo.type,
						outpatients:this.userInfo.outpatients,//是否就诊
						isIncreased:this.userInfo.isIncreased,//是否新增
						diagnose:this.userInfo.diagnose,//诊断结果
						symptom:this.userInfo.symptom,//症状
						symptomId:this.userInfo.symptomId,//症状id
						currentStatus:this.userInfo.currentStatus,//目前状况
						whereOutpatients:this.userInfo.whereOutpatients,//何处就诊
						isType:this.userInfo.type=='病假'?'1':'0',
						
					}
					// 获取提交信息
					uni.showLoading({
						title: '提交中'
					},2000);
					console.log('submit', data)
					saveLeaveApply(data).then(
						res => {
							uni.hideLoading()
							if (res.data.code == "0") {
								this.$api.showTip("提交成功", () => {
									console.log('shengq ', res.data)
									// self.notification(res.data.data.applyId)
									uni.redirectTo({
										url: "list"
									})
								});
							} else {
								this.$api.showTip(res.data.msg);
							}
						},
						err => {
							uni.hideLoading();
							this.$api.showTip('服务器错误');
						}
					);
				}).catch(errors => {

				})
			},
			// getToken() {
			// 	let self = this
			// 	wx.requestSubscribeMessage({
			// 		tmplIds: ['4y98Suoq_O67JCFh0B9VSDpQeRn5SSWgP791QAoLSEY'], //此处的id替换你要发送订阅的模板id,可在小程序后台新建模板中获取
			// 		success(res) {
			// 			wx.request({
			// 				url: `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${uni.getStorageSync('appid')}&secret=${uni.getStorageSync('secret')}`,
			// 				data: {},
			// 				success: function(res) {
			// 					self.mytoken = res.data.access_token

			// 				}
			// 			})
			// 		},
			// 		fail: function(res) {

			// 		}
			// 	})
			// },
			notification(id) {
				console.log('获取通知id', id)
				let self = this
				//下方的thing1，thing2和其他，对应的是你选取模板的模板详情中的字段名称(可在小程序后台模板查看对应的字段，要和上面的字段一样)，需要更改成你自己的
				const pushmsg = {
					"touser": 'og0wa4wzukRgZ9b8Awyh2Wf3el0U',
					"template_id": "4y98Suoq_O67JCFh0B9VSDpQeRn5SSWgP791QAoLSEY",
					"data": {
						"name2": {
							"value": "小花"
						},
						"name1": {
							"value": "小一班"
						},
						"phrase3": {
							"value": "事假"
						},
						"date4": {
							"value": this.userInfo.startTime
						},
						"time11": {
							"value": this.userInfo.endTime
						}
					},
					'page': '/pages/subPack/leave/detail?id=' + id
				}
				wx.request({
					url: 'https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=' + self.mytoken,
					data: JSON.stringify(pushmsg),
					method: 'POST',
					success: function(res) {
						console.log(res)
					}
				})
			},
			// 大计算天数
			getDays(startDate, endDate) {
				var date1Str = startDate.split("-"); //将日期字符串分隔为数组，数组元素分别为年、月、日      
				//根据年、月、日的值创建Date对象
				var date1Obj = new Date(date1Str[0], (date1Str[1] - 1), date1Str[2]);
				var date2Str = endDate.split("-");
				var date2Obj = new Date(date2Str[0], (date2Str[1] - 1), date2Str[2]);
				var t1 = date1Obj.getTime(); //返回从1970-1-1开始计算到Date对象中的时间之间的毫秒数
				var t2 = date2Obj.getTime(); //返回从1970-1-1开始计算到Date对象中的时间之间的毫秒数
				var datetime = 1000 * 60 * 60 * 24; //一天时间的毫秒值 
				var minusDays = Math.floor(((t2 - t1) / datetime)); //计算出两个日期天数差 
				var days = Math.abs(minusDays); //如果结果为负数，取绝对值
				minusDays = minusDays + 1;
				return minusDays;
			},
			openAction(text) {
				if (text == '请假类型') {
					this.actionTitle = '请选择请假类型';
					this.actions = this.leaveType
				} else if (text == '主要症状') {
					this.actionTitle = '请选择症状';
					this.actions = this.radios
				}

				this.showSex = true;
			},
			// 选择
			Select(e) {
				if (this.actionTitle == '请选择请假类型') {

					console.log('选择了那个', this.userInfo)
					this.userInfo.type = e.name;
					this.userInfo.typeId = e.id
					if (e.name == '病假') {
						this.showMalady = true
					} else {
						delete this.userInfo.symptom;
						delete this.userInfo.symptomId;
						this.showMalady = false
					}
				} else if (this.actionTitle == '请选择症状') {
					this.userInfo.symptom = e.name;
					this.userInfo.symptomId=e.id
				}

				// this.$refs.form1.validateField('userInfo.sex')
			}
		},
		onReady() {
			//如果需要兼容微信小程序，并且校验规则中含有方法等，只能通过setRules方法设置规则。
			this.$refs.form1.setRules(this.rules);
		}
	};
</script>
<style lang="less" scoped>
	.contain {
		width: 100%;
		height: 100%;
		background-color: #fff;
	}

	/deep/.u-icon__icon {
		font-size: 50rpx !important
	}
	/deep/.u-action-sheet {
		height: 200px;
		overflow: scroll;
	}
	.u-page__tag-item {
		display: inline-block;
		margin-right: 30rpx;
		margin-bottom: 10rpx;
		margin-top: 30rpx;
	}

	.content {
		padding: 30rpx 50rpx;
	}


	/deep/.uni-input-input {
		text-align: right;
	}

	/deep/.uni-input-placeholder {
		text-align: right;
	}

	/deep/.uni-textarea-placeholder {
		text-align: right;
	}

	/deep/.u-upload {
		align-items: end;
	}



	// 底部
	/deep/.u-tabbar--fixed {
		border-top: 1px solid #dadbde;
	}

	/deep/.u-icon__icon {
		// font-size: 48rpx!important
	}

	/deep/.u-tabbar-item__text {
		font-size: 26rpx
	}

	/deep/.u-form-item__body__right__content__slot {
		justify-content: end;
	}

	/deep/.u-textarea {
		text-align: end;
	}

	/deep/ .u-popup__content {
		padding-bottom: 20px !important;
	}
</style>